<?php
# Read image in base64 format and output it (assuming jpg)

@session_start();

require 'conf.php';


    function base64url_decode($base64url)
    {
        $base64 = strtr($base64url, '-_', '+/');
        $plainText = base64_decode($base64);
        return ($plainText);
    }

    function getpic($session, $username)
    { 
        global $MW_host;
        $fields = array('USR_GET_PIC_REQ' => '',
                        'SESSION' => $session,
                        'USERNAME' => $username);

        $fields = http_build_query($fields);

        $h = curl_init($MW_host); 
        curl_setopt($h, CURLOPT_POST, 1);
        curl_setopt($h, CURLOPT_POSTFIELDS, $fields); 
        curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); 

        $res = curl_exec($h);
        if(!mb_check_encoding($res, 'UTF-8'))
            $res = utf8_encode($res);
        $data = json_decode($res);
        return $data;
    }

header('Content-type: text/html; charset="utf-8"');
    
if (!isset($_SESSION['sessiontoken'])) {
    echo 'Var god logga in igen';
    exit();
} else if (!isset($_GET['username'])) {
    echo 'Du måste ange ett användarnamn';
    exit();
} else {       
    $encdata = getpic($_SESSION['sessiontoken'], $_GET['username']);    
    if ($encdata === null) {
        echo 'Ett fel uppstod i komunikationen med mellan-servern';
        exit();
    } else if (isset($encdata->error)) {
        echo $encdata->error;
        exit();
    } else if (isset($encdata->imageBase64)) {
        $data = base64url_decode($encdata->imageBase64);
        header('Content-type: image/jpeg');
        print($data);
    }
}



?>
